"""
Case Type   : 资源池化
Case Name   : 缩容单个备机，两个会话缩容同一个备机
Create At   : 2024.10
Owner       : chen
Description :
    1.执行缩容备二
    gs_dropnode -U USER -G GROUP -h hostlist
    2.新开一个会话，缩容备二
    gs_dropnode -U USER -G GROUP -h hostlist
    3.扩容备二，恢复环境
Expect      :
    1.执行成功
    2.合理报错
    3.恢复成功
"""

import os
import unittest
import time
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.ComThread import ComThread
from yat.test import Node
from yat.test import macro

class SharedStorage(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_comsh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.pri_node = Node('PrimaryDbUser')
        self.pri_root_node = Node('PrimaryRoot')
        self.sta2_node = Node('Standby2DbUser')
        self.db_host = self.sta2_node.db_host
        self.s_user = self.pri_node.ssh_user

    def test_shared_storage(self):
        text = f'''-----step1: 执行缩容备二 expect: 工具执行成功-----'''
        self.log.info(text)
        course1 = ComThread(self.pri_comsh.exec_dropnode, 
            args=(self.sta2_node, macro.DB_ENV_PATH, True,))
        course1.setDaemon(True)
        course1.start()
        time.sleep(10)

        text = f'''-----step2: 新开一个会话，缩容备二 expect: 合理报错-----'''
        self.log.info(text)
        course2 = ComThread(self.pri_comsh.exec_dropnode, 
            args=(self.sta2_node, macro.DB_ENV_PATH, True,))
        course2.setDaemon(True)
        course2.start()
        course1.join()
        res1 = course1.get_result()
        course2.join()
        res2 = course2.get_result()
        
    def tearDown(self):
        text = f'''-----step3: 恢复环境 expect: 成功-----'''
        self.log.info(text)
        cmd = f'source {macro.DB_ENV_PATH}; gs_uninstall --delete-data'
        self.log.info(cmd)
        res = self.sta2_node.sh(cmd).result()
        self.log.info(res)
        xml_path = macro.DB_XML_PATH
        cmd = f'''gs_expansion -U {self.s_user} -G \
            {self.s_user} -X {xml_path} -h {self.db_host}'''
        execute_cmd = f'''source {macro.DB_ENV_PATH};
        expect <<EOF
        set timeout 300
        spawn {cmd}
        expect "*assword*:"
        send "{self.pri_root_node.ssh_password}\\n"
        expect "*assword*:"
        send "{self.pri_node.ssh_password}\\n"
        expect "*lease repeat for database*:"
        send "{macro.GAUSSDB_INIT_USER_PASSWD}\\n"
        expect eof\n''' + '''EOF'''
        self.log.info(execute_cmd)
        res = self.pri_root_node.sh(execute_cmd).result()
        self.log.info(res)
        self.assertIn(f'{self.db_host}:\tSuccess', res)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')